package com.tools.cleanmaster.functionpage;


import android.animation.Animator;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tools.ad.EntranceType;
import com.tools.ad.util.GARecordUtils;
import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.CleanGAConstant;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.cpucool.CpuCoolInterface;
import com.tools.cleanmaster.cpucool.CpuCoolManager;
import com.tools.cleanmaster.cpucool.CpuTempInfo;
import com.tools.cleanmaster.manager.SortProcessManager;
import com.tools.cleanmaster.store.CpuCoolSharedPrefManager;
import com.tools.cleanmaster.taskmain.ProcessItem;
import com.tools.cleanmaster.ui.card.animator.AnimationListenerAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Cpu降温处理类
 */
public class FunctionCPUCoolHandler extends FunctionHandler implements CpuCoolInterface.GetCpuTempListener {
    private int mCpuDropValue;
    private double mCpuOptimizeTempValue = 0;
    private double mCpuTempValue = 0;
    private List<ProcessItem> mProcessItems;
    private boolean isProtected;
    private View cpuScanLayout;
    private TextView cpuNotification;
    private CpuTempCurveView cpuTempCurveView;
    private AppDetailListView mAppList;
    private View cpuDetailsLayout;
    private CoolDownView cpuCoolingView;
    private View cpuCoolingLayout;
    private Button mBottomBtn;
    private CoolDownScanView scanView;

    @Override
    public void init(Context context, View viewRoot) {
        super.init(context, viewRoot);
        cpuScanLayout = mViewRoot.findViewById(R.id.cpucool_scan_layout);
        cpuNotification = mViewRoot.findViewById(R.id.cpucool_scan_notification);
        cpuTempCurveView = mViewRoot.findViewById(R.id.cpucool_details_view);
        cpuDetailsLayout = mViewRoot.findViewById(R.id.cpucool_details_layout);
        cpuCoolingView = mViewRoot.findViewById(R.id.cpu_cooling_view);
        mAppList = mViewRoot.findViewById(R.id.cpucool_details_lv);
        cpuCoolingLayout = mViewRoot.findViewById(R.id.cpu_cooling_layout);
        mBottomBtn = mViewRoot.findViewById(R.id.cpucool_bottom_btn);
        scanView = mViewRoot.findViewById(R.id.cpucool_scan_view);
        mBottomBtn.setVisibility(View.GONE);
        mBottomBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startStateHandler();
                mBottomBtn.setEnabled(false);
                mBottomBtn.setText(R.string.function_cpucool_bottom_btn);
            }
        });
        if (CpuCoolManager.getInstance().isInProtectTime()) {
            isProtected = true;
            // 保护时间内，设置此次降温为0度
            CpuCoolSharedPrefManager.setCpuCoolLastTempDrop(0);
        } else {
            CpuCoolManager.getInstance().addListener(this);
            boolean needUpdate = CpuCoolManager.getInstance().getNeedUpdateTem();
            CpuCoolManager.getInstance().startGetCpuTempAsync(true, needUpdate);
            if (needUpdate) {
                CpuCoolManager.getInstance().setNeedUpdateTem(false);
            }
            isProtected = false;
        }
    }

    @Override
    public void startStateScan() {
        if (handlerListener != null) {
            handlerListener.startScan();
        }
        mViewRoot.setVisibility(View.VISIBLE);
        cpuScanLayout.setVisibility(View.VISIBLE);
        cpuNotification.setVisibility(View.VISIBLE);

        scanView.setNormal(false);
        scanView.startScan(new android.animation.AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                ArrayList<SortProcessManager.ProcessItem> list = SortProcessManager.getSortProcessManager().getProcessItems();
                if (list == null || list.isEmpty()) {
                    GARecordUtils.report(CleanApplication.getInstance(), CleanGAConstant.C_FUNC, CleanGAConstant.A_SHOW,
                            String.format(Locale.ENGLISH, CleanGAConstant.L_FUNCTION_EMPTY_RESULT, "cooler"));

                    imContext.getAdSceneManager().load(EntranceType.HOME_CPU_INTERSTITIAL);

                    //结果停留2s后，才执行完成动画
                    imContext.handleMobEmptyDelayMessage(R.id.msg_show_complete_view, 2000L);

                    FunctionItemSharedPrefs.setFunctionItemOverHandingTime(imContext, FunctionItem.CPUOVER);
                } else {
                    cpuScanLayout.setVisibility(View.GONE);
                    cpuDetailsLayout.setVisibility(View.VISIBLE);

                    mAppList.setAppsIcons(list);
                    mAppList.setIsBatteryInform(false, 40);
                    mAppList.setVisibility(View.VISIBLE);
                    mBottomBtn.setVisibility(View.VISIBLE);
                    mBottomBtn.setEnabled(true);
                    ((TextView) mViewRoot.findViewById(R.id.app_detail_text)).setText(
                            imContext.getString(R.string.function_cpucool_detail_title, list.size() + ""));
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            CpuTempInfo info = CpuCoolManager.getInstance().startGetCpuTempSync(false, true);
                            cpuTempCurveView.setCurrentTemp(info.getCpuTemp());
                        }
                    });
                    if (handlerListener != null) {
                        handlerListener.finishScan();
                        handlerListener.showAppsDetailPage();
                    }
                }
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                cpuNotification.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void startStateHandler() {
        if (handlerListener != null) {
            handlerListener.startHandler(mAppList.getHasSelected());
        }
        CpuCoolManager.getInstance().startCpuCoolAsync(mProcessItems);
        mAppList.clearAppAnimation(new AnimationListenerAdapter() {
            @Override
            public void onAnimationEnd(Animation animation) {
                mAppList.setVisibility(View.GONE);
                cpuDetailsLayout.setVisibility(View.GONE);
                cpuCoolingLayout.setVisibility(View.VISIBLE);
                cpuCoolingView.setVisibility(View.VISIBLE);
                cpuCoolingView.startSnow(new CoolDownView.SnowAnimListener() {

                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onEnd() {
                        cpuCoolingLayout.setVisibility(View.GONE);
                        mViewRoot.setVisibility(View.GONE);
                        // 处理完成后最后取消监听
                        CpuCoolManager.getInstance().removeListener(FunctionCPUCoolHandler.this);
                        if (handlerListener != null) {
                            handlerListener.finishHandler();
                        }
                    }
                });

            }
        });
    }

    @Override
    public void startStateFakeHandler() {
        if (handlerListener != null) {
            handlerListener.startScan();
        }

        imContext.getAdSceneManager().load(EntranceType.HOME_CPU_INTERSTITIAL);
        FunctionItemSharedPrefs.setFunctionItemOverHandingTime(imContext, FunctionItem.CPUOVER);

        mViewRoot.setVisibility(View.VISIBLE);
        cpuScanLayout.setVisibility(View.VISIBLE);
        cpuNotification.setText(R.string.function_cpucool_scan_normaltext);
        cpuNotification.setVisibility(View.VISIBLE);
        scanView.setNormal(true);
        scanView.startScan(new android.animation.AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                cpuScanLayout.setVisibility(View.GONE);
                mViewRoot.setVisibility(View.GONE);
                if (handlerListener != null) {
                    handlerListener.finishHandler();
                }
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
            }
        });
    }

    @Override
    public void onGetCpuTempDone(CpuTempInfo info) {
        mProcessItems = info.getProcessItems();
    }

    @Override
    public void onMakeCpuCoolDone(double coolTemp, double lastCoolTemp) {
        int nCpuTempValue = (int) mCpuTempValue == 0 ? (int) lastCoolTemp : (int) mCpuTempValue;
        int nCpuTempOptimizeValue = (int) mCpuOptimizeTempValue == 0 ? (int) coolTemp : (int) mCpuOptimizeTempValue;
        mCpuDropValue = nCpuTempOptimizeValue;
        if (mAppList.getHasSelected()) {
            CpuCoolSharedPrefManager.setCpuCoolLastTime(System.currentTimeMillis());
            CpuCoolSharedPrefManager.setCpuCoolLastTemp(nCpuTempValue);
            CpuCoolSharedPrefManager.setCpuCoolLastTempDrop(nCpuTempOptimizeValue);
            // 设置执行CPU降温后，所杀的应用进程的保护时间
            CpuCoolManager.getInstance().setAppsProtect(mProcessItems);
        }
    }
}
